"""
订单相关API路由模块
提供订单创建、查询和状态更新的接口
"""
from fastapi import APIRouter, Depends, HTTPException
from sqlmodel import Session
from typing import Dict, Any
from app.database import get_db
from app.services.order_service import OrderService


# 创建订单相关的API路由器
router = APIRouter(prefix="/orders", tags=["orders"])
"""订单API路由器，所有订单相关接口前缀为/orders，标签为orders"""


@router.post("/", response_model=Dict[str, Any])
def create_order(order_data: Dict[str, Any], db: Session = Depends(get_db)):
    """
    创建订单接口
    根据提供的订单数据创建新订单
    
    Args:
        order_data (Dict[str, Any]): 订单数据，包含必要的订单信息
        db (Session): 数据库会话，通过依赖注入获取
    
    Returns:
        Dict[str, Any]: 创建的订单信息
    
    Raises:
        HTTPException: 当创建订单失败时返回400错误
    """
    # 初始化订单服务
    order_service = OrderService(db)
    try:
        return order_service.create_order(order_data)
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/{order_number}", response_model=Dict[str, Any])
def get_order(order_number: str, db: Session = Depends(get_db)):
    """
    获取订单接口
    根据订单号查询订单信息
    
    Args:
        order_number (str): 订单编号
        db (Session): 数据库会话，通过依赖注入获取
    
    Returns:
        Dict[str, Any]: 订单信息
    
    Raises:
        HTTPException: 当订单不存在时返回404错误
    """
    # 初始化订单服务
    order_service = OrderService(db)
    # 查询订单
    order = order_service.get_order_by_number(order_number)
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
    return order


@router.put("/{order_number}/status")
def update_order_status(order_number: str, status_data: Dict[str, Any], db: Session = Depends(get_db)):
    """
    更新订单状态接口
    根据订单号更新订单状态
    
    Args:
        order_number (str): 订单编号
        status_data (Dict[str, Any]): 状态数据，包含新的状态
        db (Session): 数据库会话，通过依赖注入获取
    
    Returns:
        Dict[str, Any]: 更新后的订单信息
    
    Raises:
        HTTPException: 当订单不存在时返回404错误
        HTTPException: 当更新状态失败时返回400错误
    """
    # 初始化订单服务
    order_service = OrderService(db)
    # 查询订单是否存在
    order = order_service.get_order_by_number(order_number)
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
    
    # 更新订单状态
    try:
        return order_service.update_order_status(order.id, status_data["status"])
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))